/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gray.swing.field;

import java.awt.Container;
import gray.Field;
import snippet.Snipet;
import gray.swing.FactorySwing;
import regex.Regex;
import java.awt.FlowLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.math.BigDecimal;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 *
 * @author martin
 */
public class MoneyField extends JPanel implements Field<BigDecimal,Container>, FocusListener{
    private final JLabel _label;
    private final JTextField _field;
    private final Boolean _required;
    private final Snipet _lang;
    
    private MoneyField(final Snipet lang,final String label, final Character key, boolean required){
        super(new FlowLayout(FlowLayout.RIGHT));
        if (required)
            _label = new JLabel(label + "[required]");
        else
            _label = new JLabel(label);
        _field = new JTextField(20);
        _required = required;
        _field.addFocusListener(this);
        setFocusable(true);
                
        _label.setDisplayedMnemonic(KeyEvent.getExtendedKeyCodeForChar(key));
        _label.setLabelFor(_field);
        
        add(_label);
        add(_field);
        add(new JLabel("$"));

        _lang=lang;
    }

    public static Field<BigDecimal,Container> factory(final Snipet lang,final String label, final Character key){
        return new MoneyField(lang, label,key, false);
    }
    
    public static Field<BigDecimal,Container> factoryRequired(final Snipet lang,final String label, final Character key){
        return new MoneyField(lang, label,key, true);
    }

    @Override
    public void focusGained(FocusEvent arg0) {
    }

    @Override
    public void focusLost(FocusEvent arg0) {
        if (_field.getText().length()!=0){
            if(!Regex.validateMoney(_field.getText())){
                FactorySwing.messageError(_lang.notMoney());
                _field.setText(null);
            }
        }
    }

    @Override
    public BigDecimal input() {
        try{
            return new BigDecimal(_field.getText());
        }catch(NumberFormatException e){
            return new BigDecimal(0);
        }
    }
    
    @Override
    public Container container() {
        return this;
    }

    @Override
    public Boolean ready() {
        if (_required)
            return _field.getText().length()!=0;
        return true;
    }
}
